#include"String.h"

namespace xlf
{
	const size_t String::npos = -1;

	String::String()
	{
		_str = new char[1] {'\0'};
		_size = 0;
		_capacity = 0;
	}

	//String::String(const char* str)
	//	:_str(new char[strlen(str) + 1])
	//	, _size(strlen(str))
	//	, _capacity(strlen(str))
	//{
	//	strcpy(_str, str);
	//}
	String::String(const char* str)
		:_size(strlen(str))
	{
		_str = new char[_size + 1];
		_capacity = _size;
		strcpy(_str, str);
	}

	String::~String()
	{
		delete[] _str;
		_str = nullptr;
		_size = 0;
		_capacity = 0;
	}

	// 深拷贝（开辟新空间）
	String::String(const String& s)
	{
		_str = new char[s._capacity + 1];// 开新空间
		strcpy(_str, s._str);// 把旧空间拷贝到新空间
		_size = s._size;
		_capacity = s._capacity;
	}

	// 遍历字符
	const char* String::c_str() const { return _str;}
	size_t String::size() const { return _size; }
	size_t String::capacity() const { return _capacity; }

	char& String::operator[](size_t pos)
	{
		assert(pos < _size);
		return _str[pos];// 返回 char*
	}

	const char& String::operator[](size_t pos) const
	{
		assert(pos < _size);
		return _str[pos];// 返回 const char*
	}

	String::iterator String::begin()
	{
		return _str;
	}

	String::iterator String::end()
	{
		return _str + _size;
	}

	String::const_iterator String::begin() const
	{
		return _str;
	}
	String::const_iterator String::end() const
	{
		return _str + _size;
	}

	void String::Reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* temp = new char[n + 1];
			strcpy(temp, _str);
			delete[] _str;

			_str = temp;
			_capacity = n;
		}
	}

	void String::Push_back(char ch)
	{
		if (_capacity == _size)
		{
			size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
			Reserve(newcapacity);
		}
		_str[_size] = ch;
		_str[_size + 1] = '\0';
		++_size;
	}

	void String::append(const char* str)
	{
		size_t len = strlen(str);
		if (_size + len > _capacity)
			Reserve(_size + len);
		strcpy(_str + len, str);
		_size += len;
	}

	String& String::operator+=(char ch)
	{
		Push_back(ch);
		return *this;
	}

	String& String::operator+=(const char* ch)
	{
		append(ch);
		return *this;
	}

	void String::insert(size_t pos, char ch)
	{
		assert(pos <= _size);
		if (_size == _capacity)
		{
			size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
			Reserve(newcapacity);
		}
		size_t end = _size + 1;
		while (end > pos)// 挪动数据
		{
			_str[end] = _str[end - 1];
			--end;
		}
		_str[pos] = ch;
		++_size;
	}

	// 插入一个字符串
	void String::insert(size_t pos, const char* str)
	{
		assert(pos <= _size);
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			Reserve(_size + len);
		}
		size_t end = _size + len;
		while (end >= pos + len)
		{
			_str[end] = _str[end - len];
			--end;
		}
		memcpy(_str + pos, str, len);
		_size += len;
	}


}




